package com.tanhua.server.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.intercepter.UserThreadLocal;
import com.tanhua.server.service.VideosService;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class VideosServiceImpl implements VideosService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;


    /**
     * 分页查询视频数据
     */
    @Override
    public PageResult findVideos(Integer page, Integer pageSize) {

        //videoAPi根据page,pagesize查询
        List<Video> list = videoApi.queryVideoList(page, pageSize);

        //5、提取视频列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //6、查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //7、构建返回值
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo info = map.get(video.getUserId());
            if (info != null) {
                VideoVo vo = VideoVo.init(info, video);
                vos.add(vo);
            }
        }
        return new PageResult(page, pageSize, 0l, vos);
    }


    //上传小视频
    @SneakyThrows
    @Override
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) {
        if (videoFile.isEmpty() || videoThumbnail.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }
        //1.将视频上传FastDFs,获取访问url
        String filename = videoFile.getOriginalFilename();
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath =
                fastFileStorageClient.uploadFile(videoFile.getInputStream(),
                        videoFile.getSize(), filename, null);
        String videoUrl =
                webServer.getWebServerUrl() + storePath.getFullPath();
        //2.将封面图片上传到oss,获取URL
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(),
                videoThumbnail.getInputStream());
        //构造videos对象
        Long userId = UserThreadLocal.getUserId();
        Video video = new Video();
        video.setUserId(userId);
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("未到终局,你我皆黑马!");
        //调用APi保存数据
        String vid = videoApi.save(video);
        if (StringUtils.isEmpty(vid)) {
            throw new BusinessException(ErrorResult.error());
        }
    }


}
